/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package simplepushserver.file;

import java.awt.Container;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.JFileChooser;


/**
 *
 * @author Fille
 */
public class FileUtils {

    public static File[] listFilesAsArray(File directory, boolean recurse){
        LinkedList<File> files = listFiles(directory, recurse);
        File[] arr = new File[files.size()];
        return files.toArray(arr);
    }
    public static ArrayList<File> fileArray2List(File[] a, boolean includeDirectory){
        ArrayList<File> alist = new ArrayList<File>();
        for(File f : a){
            if(f.isDirectory()) {
                if(includeDirectory)
                    alist.add(f);
                alist.addAll(listFiles(f, includeDirectory));
            }else{
                alist.add(f);
            }
        }
        return alist;
    }
    
    public static LinkedList<File> listFiles(File directory, boolean includeDirectory){
        LinkedList<File> files = new LinkedList<File>();
        File[] entries = directory.listFiles();
        for (File current:entries){
            if (current.isDirectory()){
                if(includeDirectory) {
                    files.add(current);
                }
                files.addAll(listFiles(current, includeDirectory));
            }else{
                files.add(current);
            }
        }
        return files;
    }
    public static long getFileSizeInBytes(File fil){
        try {
            FileInputStream filenIn = new FileInputStream(fil);
            return filenIn.available();
        }catch(Exception e){
           e.printStackTrace();
           return -1;
        }
    }
    public static void sendFileHeader(DataOutputStream dataUt,DataInputStream dataIn, String offset, File fil, int BLOCKSIZE) throws IOException{
        print("SENDING FILEINFO!");
        long filesize=FileUtils.getFileSizeInBytes(fil);
        print("#FileUtils: Sending Size: "+filesize);
        dataUt.writeLong(filesize);
        print(dataIn.readBoolean()+"");
        print("#FileUtils: Sending Blocksize: "+BLOCKSIZE);
        dataUt.writeInt(BLOCKSIZE);
        print(dataIn.readBoolean()+"");
        print("#FileUtils: Sending Filename: "+offset);
        dataUt.writeChars(offset);
        print("#FileUtils: Sending EOF-flag for Filename: \""+offset+"|\" ");
        dataUt.writeChar('|');
        print(dataIn.readBoolean()+"");
        print("STOPPED SENDING FILEINFO!");
    }
    
    public static ArrayList<File> FileChooser(Container con, boolean includeDirectory){
        JFileChooser diag = new JFileChooser();
        diag.setMultiSelectionEnabled(true);
        diag.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        diag.setDialogType(JFileChooser.OPEN_DIALOG);
        diag.setDragEnabled(true);
        diag.setDialogTitle("Välj Filer/Mappar");
        if(diag.showOpenDialog(con) != JFileChooser.APPROVE_OPTION){
            return null;
        }
        ArrayList<File> lista = new ArrayList<File>();
        lista.add(diag.getCurrentDirectory());
        lista.addAll(fileArray2List(diag.getSelectedFiles(), includeDirectory));
        return lista;
    }
    public static void printFileList(List lista){
        if(lista!=null && !lista.isEmpty()){
            for (Object ob : lista) {
                System.out.println(ob.toString());
            }
        }
    }
    
    public static String getDirOffset(File mainDir, File current){
        String maindirpath = mainDir.getAbsolutePath();
        String currentpath = current.getAbsolutePath();
        
        String s = currentpath.substring(maindirpath.length()+1, currentpath.length());
        //System.out.println( "Substring ("+ maindirpath.length()+1 +" , " + currentpath.length()+") = "+s );
        return s;
    }
    public static File fileNameSeperator(String in){

        int index = in.lastIndexOf("\\");
        return new File(in.substring(0, index+1), in.substring(index+1));
    }

    public static int countFilesInList(List<File> alist){
        int i=0;
        ArrayList<File> lista = new ArrayList<File>(alist);
        for(File f : lista){
            if(f.isFile()) {
                i++;
            }
        }
        return i;
    }
    public static int countFiles(File folder){
        int nr = 0;
        for(File f : folder.listFiles()){
            if(f.isDirectory())
                nr+=countFiles(f);
            else
                nr++;
        }
        return nr;
    }
    public static int countFiles(List<File> folders){
        int nr=0;
        for(File f:folders){
            nr+=countFiles(f);
        }
        return nr;
    }

    public static long getTotalFileSize(File[] flist){
        long size=0;
        for(File f : flist){
            if(f.isDirectory()){
                LinkedList<File> ny = listFiles(f, false);
                printFileList(ny);
                size+=getTotalFileSize(ny);
            }else{
                size+=getFileSizeInBytes(f);
            }
        }
        return size;
    }
    public static long getTotalFileSize(List<File> flist){
        long size=0;
        for(File f : flist){
            if(f.isDirectory()){
                LinkedList<File> ny = listFiles(f, false);
                printFileList(ny);
                size+=getTotalFileSize(ny);
            }else{
                size+=getFileSizeInBytes(f);
            }
        }
        return size;
    }
    public static long getTotalFileSize(File selectedFile) {
        if(selectedFile.isDirectory()){
            return getTotalFileSize(listFiles(selectedFile, false));
        }else{
            return getFileSizeInBytes(selectedFile);
        }
    }

    public static void print(String text){
        System.out.println(text);
    }

    public static boolean containsWord(String word, String filename){
        return filename.matches(".*\\W"+word+"\\W.*");
    }

    public static String cleanFilename(String name){
        StringBuilder sb = new StringBuilder();
        for (StringTokenizer  st = new StringTokenizer(name);  st.hasMoreTokens();) {
            sb.append(toLetter(st.nextToken()));
        }
        return sb.toString();
    }
    public static String toLetter(String s){
        char[] arr = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char c : arr) {
            if(Character.isLetter(c)){
                sb.append(c);
            }
        }
        return sb.toString();
    }
}